package org.example.lock;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Sync3 {
    List<Character> result = new ArrayList<>(); // 共享数组
    volatile int total = 5; // 总写入次数（由A线程决定）
    volatile int current = 0; // 当前写入次数
    volatile String currentThread = "A"; // 当前执行线程标识
    final Object lock = new Object(); // 同步锁

    Runnable a = () -> {
        while (true) {
            synchronized (lock) {
                // 等待当前执行线程为A且未达到总次数
                while (!currentThread.equals("A") && current < total) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (current >= total) break; // 达到总次数退出

                result.add('a');
                current++; // 仅A线程递增计数器
                currentThread = "B"; // 切换到B线程
                lock.notifyAll();  // 通知其他线程
            }
        }
    };
    Runnable b = () -> {
        while (true) {
            synchronized (lock) {
                // 等待当前执行线程为B且未达到总次数
                while (!currentThread.equals("B") && current <= total) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                result.add('l');
                currentThread = "C"; // 切换到C线程
                lock.notifyAll();

                if (current >= total) break;
            }
        }
    };
    Runnable c = () -> {
        while (true) {
            synchronized (lock) {
                // 等待当前执行线程为C且未达到总次数
                while (!currentThread.equals("C") && current <= total) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                result.add('i');
                currentThread = "A"; // 切换回A线程
                lock.notifyAll();
                if (current >= total) break;
            }
        }
    };

    private void test() throws InterruptedException {
        Thread threada = new Thread(a);
        Thread threadb = new Thread(b);
        Thread threadc = new Thread(c);
        threada.start();
        threadb.start();
        threadc.start();

        threada.join();
        threadb.join();
        threadc.join();

        System.out.println(Arrays.toString(result.toArray()));
    }


    public static void main(String[] args) {
        try {
            new Sync3().test();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
